#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""
Pillow的基本使用
"""

from PIL import Image
from PIL import ImageFilter
from PIL import ImageEnhance
import os

def main():
    """
    图像操作
    :return:
    """

    img = Image.open("D:/Tools/pyCharm/images/temp/dogs.png")
    # 输出图片格式
    print(img.format)
    # 输出图像的色彩模式，"L"：灰度图像，"RGB"：真彩色图像，"CMYK"：出版图像
    print(img.mode)
    # 输出图片大小，返回一个二元组，表示图像的宽度和高度（px）。
    print(img.size)

    # 调整尺寸
    img_resize = img.resize((256, 256))
    img_resize.save("D:/Tools/pyCharm/images/temp/dogs_resize.png")

    # 旋转 -> 逆时针旋转45度
    img_rotate = img.rotate(45, expand=True)
    img_rotate.save("D:/Tools/pyCharm/images/temp/dogs_rotate.png")

    # 灰度处理
    om = img.convert('L')
    om.save("D:/Tools/pyCharm/images/temp/dogs_gray.png")
    # 出版图像处理
    om = img.convert('CMYK')
    om.save("D:/Tools/pyCharm/images/temp/dogs_CMYK.jpg")
    # om.show()

    # 图片的轮廓
    om = img.filter(ImageFilter.CONTOUR)
    om.save("D:/Tools/pyCharm/images/temp/dogs_contour.png")

    # 增强 -> 对比度为初始的10倍
    om = ImageEnhance.Contrast(img).enhance(20)
    om.save("D:/Tools/pyCharm/images/temp/dogs_contrast.png")

    # 图像转换
    # 左右对换
    out = img.transpose(Image.FLIP_LEFT_RIGHT)
    out.save("D:/Tools/pyCharm/images/temp/dogs_FLIP_LEFT_RIGHT.png")
    # 上下对换
    out = img.transpose(Image.FLIP_TOP_BOTTOM)
    out.save("D:/Tools/pyCharm/images/temp/dogs_FLIP_TOP_BOTTOM.png")



    # 两张图片相加 alpha表示img1和img2的比例参数
    img_blend = Image.blend(om, img, alpha=10)
    img_blend.save("D:/Tools/pyCharm/images/temp/dogs_blend.png")

    # 点操作
    om1 = img.point(lambda i: i*5)   # 对每个点进行50%的加强
    om.save("D:/Tools/pyCharm/images/temp/dogs_point.png")





    # 缩略图
    img.thumbnail((128, 128), Image.ANTIALIAS)
    img.save("D:/Tools/pyCharm/images/temp/dogs_thumbnail"+".jpg", "JPEG")
    # img.show()

    # fileList = ["D:/Tools/pyCharm/images/temp/dogs.png",
    #             "D:/Tools/pyCharm/images/temp/dogs_resize.png",
    #             "D:/Tools/pyCharm/images/temp/dogs_rotate.png"]
    #
    # convertImageFormat(fileList, ".jpg")


def convertImageFormat(fileList, suffix):
    """
    转换图片格式（修改后缀）
    :param fileList: 图片列表
    :param suffix: 后缀
    :return:
    """
    for file in fileList:
        outFile = os.path.splitext(file)[0] + suffix
        if file != outFile:
            try:
                Image.open(file).save(outFile)
            except IOError:
                print("cannot convert", file)


def merge():
    """
    图片裁剪、图像粘贴（合并）
    :return:
    """
    img1 = Image.open("D:/Tools/pyCharm/images/temp/dogs.png")
    img2 = Image.open("D:/Tools/pyCharm/images/temp/dogs_contrast.png")
    # 设置要裁剪的区域
    box = (100, 100, 300, 300)
    region = img2.crop(box)
    # 粘贴box大小的region到img1图片对象中 左上角原点位置
    img1.paste(region, (0, 0))
    img1.save("D:/Tools/pyCharm/images/temp/dogs_paste.png")

if __name__ == '__main__':
    main()
    merge()


